import {
  getMemberCard,
  getCardFlzkFrdb
} from '@/api/api'
import {
  CARD_MEMBER_INFO
} from '@/utils/constant'

const user = {
  state: {
    cardInfo: {},
    pocketInfo: {},
  },
  mutations: {
    SET_CARD_INFO(state, payload) {
      state.cardInfo = payload;
    },
    SET_POCKET_INFO(state, payload) {
      state.pocketInfo = payload;
    }
  },
  actions: {
    readLocalCardInfo({ commit }) {
      let localUserInfo = uni.getStorageSync(CARD_MEMBER_INFO) || {};
      // 本地信息有效才往往全局变量存
      if (localUserInfo.unionid) {
        commit('SET_CARD_INFO', localUserInfo);
      }
    },
    requestCardInfo({ commit }) {
      return new Promise(async (resolve, reject) => {
        let mmcards = await getMemberCard({
          query: {
            cardtype: "MEMBER_CARD"
          }
        });
        console.log("home => getMemberCardInfoAndDrawCode >> getMemberCard >>> 👇");
        if (mmcards.data.status == 1 && mmcards.data.data.length > 0) {
          mmcards.data.data.forEach((currentValue, index, arr) => {
            if (currentValue.type == "MEMBER_CARD") {
              uni.setStorageSync(CARD_MEMBER_INFO, currentValue);
              commit('SET_CARD_INFO', currentValue);
              resolve(currentValue);
            } else {
              reject(mmcards);
            }
          });
        } else {
          reject(mmcards);
        }
      });
    },
    requestPocketInfo({ state, commit }) {
      return new Promise(async(resolve, reject) => {
        console.log(state);
        if (!state.cardInfo.wxcardno) {
          reject('wxcardno not exist');
        }
        let result = await getCardFlzkFrdb({
          query: {
            code: state.cardInfo.wxcardno
          }
        });
        console.log("home => onShow >> getCardFlzkFrdb 👇");
        console.log(result.data);
        if (result.data.status == 1) {
          /**
           * flzk 余额
           * frdb 零钱包
           * frdbsfz 奥特莱斯积分
           * ye 积分
           */
          commit('SET_POCKET_INFO', result.data.data);
          resolve(result.data.data);
        } else {
          reject(result);
        }
      });
    }
  },
}

export default user;